package com.itheima.d3_tcp.no4;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

//目标：掌握利用多线程优化tcp服务端的方式
public class ServerDemo04 {
    public static void main(String[] args) throws Exception {
        //1.创建ServerSocket对象，负责的是接收客户端的连接（Socket对象）
        ServerSocket server = new ServerSocket(10006);

        //创建线程池
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                //核心线程数
                2,
                //总线程数
                3,
                //临时线程存活时间数字
                8,
                //时间单位
                TimeUnit.SECONDS,
                //任务队列
                new ArrayBlockingQueue<>(2),
                //线程工厂
                Executors.defaultThreadFactory(),
                //拒绝策略
                new ThreadPoolExecutor.AbortPolicy()
        );


        //2.不断的接收多个客户端的连接，accept方法需要不断的调用
        while (true) {
            Socket socket = server.accept();

            //3.为了不影响主线程继续循环调用accept方法获取其他客户端的连接，socket的处理交给子线程
            ServerRunnable runnable = new ServerRunnable(socket);
            //Thread thread = new Thread(runnable);
            //thread.start();
            pool.execute(runnable);
        }
    }
}


